﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ProgNetComponents.Data.SqlCe
{
    /// <summary>
    /// SchemaChecker for Sql Server CE
    /// </summary>
    public class SqlCeSchemaChecker : SchemaChecker
    {
        /// <summary>
        /// Creates SqlCeSchemaChecker instance
        /// </summary>
        /// <param name="manager"></param>
        public SqlCeSchemaChecker(SqlCeDataManager manager)
            : base(manager)
        {

        }

        /// <summary>
        /// Fills SchemaDataSet with DB schema
        /// </summary>
        /// <param name="schema"></param>
        protected override void FillSchemaDataSet(SchemaDataSet schema)
        {
            schema.Clear();
            string query = "SELECT DISTINCT TABLE_NAME, COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS";

            Manager.FillTable(schema.COLUMNS, query);
            query = "SELECT DISTINCT CONSTRAINT_TABLE_NAME AS FOREIGN_TABLE, "+
                " CONSTRAINT_NAME, " +
                " UNIQUE_CONSTRAINT_TABLE_NAME AS PRIMARY_TABLE, " +
                " DELETE_RULE FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS";

            Manager.FillTable(schema.REF_CONSTRAINTS, query);

            query = "SELECT REF.CONSTRAINT_NAME, PCOLS.COLUMN_NAME AS PRIMARY_COLUMN, "
                 + " FCOLS.COLUMN_NAME AS FOREIGN_COLUMN FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS REF, "
                 + " INFORMATION_SCHEMA.KEY_COLUMN_USAGE PCOLS, INFORMATION_SCHEMA.KEY_COLUMN_USAGE FCOLS "
                 + " WHERE REF.CONSTRAINT_NAME = FCOLS.CONSTRAINT_NAME AND REF.UNIQUE_CONSTRAINT_NAME = PCOLS.CONSTRAINT_NAME "
                 + "AND FCOLS.ORDINAL_POSITION = PCOLS.ORDINAL_POSITION";
            Manager.FillTable(schema.REF_CONSTRAINTS_COLUMNS, query);
        }
    }
}
